package org.micode.common.utils;

import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Utils {

	/**
	 * MD5加密算法
	 *
	 * @param sourceStr
	 *            要加密的明文
	 * @return 加密后的密文
	 */
	public final static String stringMD5(String sourceStr) {
		byte[] btInput = sourceStr.getBytes();
		return byteMD5(btInput);
	}

	public final static String stringMD5(String sourceStr, Charset charset) {
		byte[] btInput = sourceStr.getBytes(charset);
		return byteMD5(btInput);
	}

	public static String byte2hex(byte[] buf) {
		StringBuffer sBuffer = new StringBuffer();
		for (int i = 0; i < buf.length; i++) {
			int hi = buf[i] >> 4 & 0x0f;
			int lo = buf[i] & 0x0f;
			sBuffer.append((char) (hi > 9 ? (hi - 10 + 'A') : (hi + '0')));
			sBuffer.append((char) (lo > 9 ? (lo - 10 + 'A') : (lo + '0')));
		}
		return sBuffer.toString();
	}

	private final static String byteMD5(byte[] btInput) {
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'A', 'B', 'C', 'D', 'E', 'F' };
		try {
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			mdInst.update(btInput);
			byte[] md = mdInst.digest();
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			byte byte0;

			for (int i = 0; i < j; i++) {
				byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}

			return new String(str);
		} catch (Exception e) {
			return null;
		}
	}

	public static String byteMD5(ByteBuffer btInput) {
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'A', 'B', 'C', 'D', 'E', 'F' };

		try {
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			mdInst.update(btInput);
			byte[] md = mdInst.digest();
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			byte byte0;

			for (int i = 0; i < j; i++) {
				byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}

			return new String(str);
		} catch (Exception e) {
			return null;
		}
	}

	public static String getMD5(String str) throws NoSuchAlgorithmException {
		MessageDigest md = MessageDigest.getInstance("MD5");
		md.update(str.getBytes());
		return new BigInteger(1, md.digest()).toString(16);
	}

	public static void main(String args[]) {
		// admin,12345678,,3C2C28608BF517CBF83E2345779C804B
		try {
			String s_pwd = MD5Utils.getMD5("18923714596").toLowerCase();
			String s_pwdAndNo = MD5Utils.getMD5(s_pwd + "18923714596");
			String scr = s_pwdAndNo.toUpperCase();
			System.out.println("明文密码MD5: " + s_pwd);
			System.out.println("明文密码MD5后+A0001: " + s_pwdAndNo);
			System.out.println("密文密码MD5: " + scr);
			System.out.println("   需要的是: 86872B8D486CC0045719C384C9A77246");
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
}
